package com.example.springboot.controller;

import com.example.springboot.entity.User;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @PostMapping
    public Integer save(@RequestBody User user) {//新增或修改
        return userService.insertUser(user);
    }

    @GetMapping
    public List<User> findAll() {//查询所有
        return userMapper.getAll();
    }

    @DeleteMapping("/{id}")
    public Integer delete(@PathVariable Integer id) {//删除
        return userMapper.deleteByID(id);
    }

    //分页查询
    //接口路径：/users/page?page=1&size=10
    //@RequestParam接受
    //limit第一个参数 = (page-1)*pagesize
    //limit第二个参数 = pagesize
    @GetMapping("/page")
    public Map<String, Object> findPage(@RequestParam Integer pageNum,
                                        @RequestParam Integer pageSize,
                                        @RequestParam String username) {
        pageNum = (pageNum - 1) * pageSize;
        username = "%" + username + "%";
        List<User> data = userMapper.selectPage(pageNum, pageSize,username);
        Integer total = userMapper.selectTotal(username);
        Map<String, Object> result = new HashMap<>();
        result.put("data", data);
        result.put("total", total);
        return result;
    }

}
